package com.alinesno.cloud.operation.cmdb.controller.manager;

import java.io.File;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alinesno.cloud.operation.cmdb.advice.ConvertCode;
import com.alinesno.cloud.operation.cmdb.common.constants.BusinessStatusEnum;
import com.alinesno.cloud.operation.cmdb.common.constants.GoodsEnum;
import com.alinesno.cloud.operation.cmdb.common.constants.HasStatusEnum;
import com.alinesno.cloud.operation.cmdb.common.excel.PoiExcelExport;
import com.alinesno.cloud.operation.cmdb.controller.BaseController;
import com.alinesno.cloud.operation.cmdb.entity.MachineEntity;
import com.alinesno.cloud.operation.cmdb.entity.OrderInfoEntity;
import com.alinesno.cloud.operation.cmdb.entity.ServerEntity;
import com.alinesno.cloud.operation.cmdb.repository.BudinessServerRepository;
import com.alinesno.cloud.operation.cmdb.repository.MachineRepository;
import com.alinesno.cloud.operation.cmdb.third.data.QiniuUploadTool;
import com.alinesno.cloud.operation.cmdb.web.bean.FileMeta;
import com.alinesno.cloud.operation.cmdb.web.bean.JqDatatablesPageBean;
import com.alinesno.cloud.operation.cmdb.web.bean.MachineBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResponseBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResultGenerator;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;

/**
 * 商品管理
 * 
 * @author WeiXiaoJin
 * @since 2018年9月9日 下午9:26:41
 */
@Controller
@RequestMapping("/manager/")
public class ManagerMachineController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private MachineRepository machineRepository;

	@Autowired
	private BudinessServerRepository budinessServerRepository;

	@Autowired
	private QiniuUploadTool qiniuUploadTool;
	
	@Value("${excel.temp.dir}")
	private String stackFileExport ; // 输出路径  

	@GetMapping("/machine_list")
	public String list(Model model) {
		createMenus(model);

		return WX_MANAGER + "machine_list";
	}
	

	@GetMapping("/machine_import_data")
	public String importData(Model model) {
		return WX_MANAGER + "machine_import_data";
	}

	@GetMapping("/machine_add")
	public String goodsAdd(Model model) {

		// 列出所有母机
		Iterable<ServerEntity> servers = budinessServerRepository.findAllByMasterCodeAndHasStatus(
				currentManager().getMasterCode(), BusinessStatusEnum.NORMAL.getCode(), null);
		model.addAttribute("servers", servers);

		return WX_MANAGER + "machine_add";
	}
	
	 @RequestMapping(value="/machine_upload_data", method = RequestMethod.POST)
	    public @ResponseBody LinkedList<FileMeta> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
	    	
	    	LinkedList<FileMeta> files =  qiniuUploadTool.uploadLocal(request , stackFileExport);
	    	FileMeta f = files.get(0) ; 
	    	String filePath = f.getFilePath() ;
	    	
	    	logger.debug("文件保存路径:{} , 保存路径:{}" , filePath , stackFileExport);
	    
	    	ImportParams params = new ImportParams();
	        List<MachineEntity> result = ExcelImportUtil.importExcel(new File(filePath),MachineEntity.class, params);
	        
	        for (MachineEntity e : result) {
	            logger.debug(ReflectionToStringBuilder.toString(e));
	           
	            String masterMachineIP = e.getMasterMachineIP() ; 
	            ServerEntity server = budinessServerRepository.findByServerName(masterMachineIP) ; 
	           
	            if(server != null) {
					e.setMasterMachine(server.getId()); 
					e.setMasterMachineIP(masterMachineIP);  
					e.setMasterCode(currentManager().getMasterCode());
					
					e.setHasStatus(HasStatusEnum.NORMARL.getCode());
					
					machineRepository.save(e) ; 
	            }
	        }
	        
	    	return files ; 
	    }


	@GetMapping("/machine_modify/{id}")
	public String goodsModify(Model model, @PathVariable("id") String id) {
		logger.debug("id = {}", id);

		MachineEntity bean = machineRepository.findById(id).get();
		model.addAttribute("bean", bean);

		// 列出所有母机
		Iterable<ServerEntity> servers = budinessServerRepository.findAllByMasterCodeAndHasStatus(
				currentManager().getMasterCode(), BusinessStatusEnum.NORMAL.getCode(), null);
		model.addAttribute("servers", servers);

		return WX_MANAGER + "machine_modify";
	}

	@ResponseBody
	@GetMapping("/machine_delete/{id}")
	public ResponseBean<String> goodsDelete(Model model, @PathVariable("id") String id) {
		logger.debug("id = {}", id);
		machineRepository.deleteById(id);
		return ResultGenerator.genSuccessMessage("删除成功.");
	}

	/**
	 * 数据列表
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ConvertCode
	@ResponseBody
	@GetMapping("/machine_list_data")
	public Object memberListData(Model model, JqDatatablesPageBean page, String runnerStatus) {
		return this.toPage(model, page.buildFilter(MachineEntity.class, request), machineRepository, page);
	}

	/**
	 * 修改上下架
	 * 
	 * @param model
	 * @return
	 */
	@ResponseBody
	@PostMapping("/machine_sale")
	public ResponseBean<String> goodsSale(Model model, String status, String id) {
		logger.debug("商品{} , 修改状态:{}", id, status);

		MachineEntity goods = machineRepository.findById(id).get();
		if (goods == null) {
			return ResultGenerator.genFailMessage("商品查询为空.");
		}
		goods.setUpdateTime(new Date());
		goods.setMachineStatus(status);

		machineRepository.save(goods);

		return ResultGenerator.genSuccessResult(GoodsEnum.getStatus(status).getCode());
	}

	/**
	 * 保存添加
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/machine_add_save", method = RequestMethod.POST)
	public ResponseBean<String> saveAdd(Model model, /* @RequestParam("file") MultipartFile file,*/ MachineEntity bean) {

		bean.setMachineStatus(GoodsEnum.SALE.getCode());

		// String netUrl = qiniuUploadTool.uploadFile(file) ;
		// if(StringUtils.isBlank(netUrl)) {
		// return ResultGenerator.genFailMessage("图片上传失败.") ;
		// }
		// logger.debug("net url = {} , bean = {}", netUrl,
		// ToStringBuilder.reflectionToString(bean));
		// bean.setMachinePic(netUrl);

		bean.setMasterCode(currentManager().getMasterCode());
		bean.setAddTime(new Date());
		bean.setUpdateTime(new Date());

		machineRepository.save(bean);

		return ResultGenerator.genSuccessMessage("保存成功.");
	}

	/**
	 * 保存修改订单
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@PostMapping("/machine_modify_save")
	public ResponseBean<String> saveModify(Model model, MultipartFile file, MachineBean vo, String id) {
		MachineEntity bean = machineRepository.findById(id).get();

		if (bean == null) {
			return ResultGenerator.genFailMessage("查询商品信息为空.");
		}

		if (file != null) {
			String netUrl = qiniuUploadTool.uploadFile(file);
			if (StringUtils.isNoneBlank(netUrl)) {
				vo.setMachinePic(netUrl);
			}
		}

		BeanUtils.copyProperties(vo, bean);
		logger.debug("bean = {}", ToStringBuilder.reflectionToString(bean));

		machineRepository.save(bean);

		return ResultGenerator.genSuccessMessage("修改成功.");
	}
	
	/**
	 * 数据导出
	 * @param model
	 * @param page
	 * @return
	 */
	@ResponseBody
	@PostMapping("/machine_export")
	public ResponseBean<String> databaseExport(Model model, JqDatatablesPageBean page) {
		
		List<MachineEntity> listPage = this.toExport(model, page.buildFilter(OrderInfoEntity.class, request), machineRepository, page , null);
		boolean b = false; 
		String saveName = null ; 
		
		if(listPage != null && listPage.size()>0) {
			
			saveName = UUID.randomUUID().toString()+".xls" ;  
			PoiExcelExport pee = new PoiExcelExport(stackFileExport , saveName ,"详情");
			
			String column[] = {"dbaLoginName","dataSpaceName","dataSpaceSize","indexSpaceName","indexSpaceSize","spaceDesc","managerMan","hostname","hostIp","sendTime","endTime"};
			String title[] = {"登陆名称","数据库空间","数据库空间大小","索引空间","索引空间大小","数据库使用描述","管理员","主机名称","主机IP","开始使用时间","开始使用时间"} ; 
			int size2[] = {15,20,20,20,20,23,15,15,15,20,20};
			
			pee.wirteExcel(column, title , size2 , listPage);
			logger.debug("list page = {}" , listPage);
			b = true ; 
		}
		
		return b ? ResultGenerator.genSuccessMessage(saveName) : ResultGenerator.genFailMessage("保存失败.");
	}


	@ResponseBody
	@RequestMapping("/machine_all")
	public List<MachineEntity> masterHost(Model model) {
		List<MachineEntity> list = machineRepository.findAllByMasterCode(currentManager().getMasterCode()) ; 
		for(MachineEntity e : list) {
			e.setMachineName("【"+e.getMachineIp()+"】-【"+e.getMachineName()+"】");
		}
		return list ; 
	} 

}
